package com.yc.txx.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.txx.entity.Car;
import com.yc.txx.mapper.CarMapper;
import com.yc.txx.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.List;

/**
 * <p>
 * 天下行租车-车辆表-10 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2024-05-07
 */
@RestController
@RequestMapping("/txx/car")
public class CarController {

    @Autowired
    CarMapper carMapper;

    JedisPool jedisPool = new JedisPool("127.0.0.1",6379);
    ObjectMapper mapper = new ObjectMapper();

    @RequestMapping("query")
    List<Car> query(Car car) throws IOException{
        if(car.getPrice().intValue() == 3 &&
                Utils.isEmpty(car.getModel() ) &&
                Utils.isEmpty(car.getBrand()) &&
                Utils.isEmpty(car.getSort())
        ) {
            Jedis jedis = jedisPool.getResource();
            try{
                if(jedis.exists("cars")){
                    String json = jedis.get("cars");
                    List list = mapper.readValue(json, List.class);
                    System.out.println("--------- redis cars -----------");
                    return list;
                } else {
                    List<Car> list = carMapper.select(car);
                    String json = mapper.writeValueAsString(list);
                    jedis.set("cars",json);
                    System.out.println("--------- mysql cars -----------");
                    return list;
                }
            }finally {
                jedisPool.returnResource(jedis);
            }
        } else {
            System.out.println("--------- mysql cars -----------");
            return carMapper.select(car);
        }
    }

    @RequestMapping("queryBrand")
    List<?> queryBrand() throws IOException {
        Jedis jedis = jedisPool.getResource();
        try{
            if(jedis.exists("brandItems")){
                String json = jedis.get("brandItems");
                List list = mapper.readValue(json, List.class);
                System.out.println("--------- redis brandItems -----------");
                return list;
            } else {
                List<String> list = carMapper.selectBrand();
                String json = mapper.writeValueAsString(list);
                jedis.set("brandItems",json);
                System.out.println("--------- mysql brandItems -----------");
                return list;
            }
        }finally {
            jedisPool.returnResource(jedis);
        }
    }


    @RequestMapping("selectCarDetail")
    Car selectCarDetail(String id){
        return carMapper.selectCarDetail(id);
    }
}
